package com.blb.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blb.service.BaseService;
import com.blb.service.impl.BaseServiceImpl;
import com.blb.utils.UUIDUtils;
import com.blb.web.base.BaseServlet;

/**
 * @author Administrator
 *
 */
@WebServlet("/admin/user/*")
public class UserServlet extends BaseServlet {
	
	private BaseService service = new BaseServiceImpl();
	
	private static final long serialVersionUID = 7060561389976928528L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		super.forward(request, response, this.getClass());
	}

	/**
	 * 登录方法
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			String username = getNotNullParam("username");
			String password = getNotNullParam("password");
			List<Map<String, Object>> list = service.get("SELECT * FROM t_user u WHERE u.`username` = ? and u.`password` = ?", username, password);
			if (list.isEmpty()) {
				request.setAttribute("msg", "登录失败："+"账号或密码不正确");
				response("login");
			}else {
				request.getSession().setAttribute("user", list.get(0));
				request.getSession().setAttribute("user_id", list.get(0).get("id"));
				response("index");
			}
		} catch (SQLException e) {
			e.printStackTrace();
			request.setAttribute("msg", "登录失败：请稍后再试或联系管理员");
			response("login");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "登录失败："  + e.getMessage());
			response("login");
		}
	}
	
	/**
	 * 注册
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			String username = getNotNullParam("username");
			String password = getNotNullParam("password");
			String confirmPassword = getNotNullParam("confirmPassword");
			if (!confirmPassword.equals(password)) {
				throw new Exception("两次密码不一致");
			}
			List<Map<String, Object>> list = service.get("select * from t_user u where u.username = ?", username);
			if (!list.isEmpty()) {
				throw new Exception("账号已存在，请修改账号");
			}
			service.execute("INSERT INTO `t_user` (`id`, `username`, `password`)VALUES(?, ?, ?)", UUIDUtils.getId(), username, password);
			response("login");
		} catch (SQLException e) {
			e.printStackTrace();
			request.setAttribute("msg", "注册失败：请稍后再试或联系管理员");
			response("register");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "注册失败："  + e.getMessage());
			response("register");
		}
	}
	
}
